import http.client
import hashlib
import urllib
import random
import json


def trans(q):
    # 百度appid和密钥需要通过注册百度【翻译开放平台】账号后获得
    appid = '20240319001998458'  # 填写你的appid
    secretKey = 'qgqZPwt50dI5zQp7THYR'  # 填写你的密钥

    httpClient = None
    myurl = '/api/trans/vip/fieldtranslate'

    fromLang = 'auto'
    toLang = 'en'
    salt = random.randint(32768, 65536)
    # q = '苹果'
    domain = 'aerospace'
    sign = appid + q + str(salt) + domain + secretKey
    sign = hashlib.md5(sign.encode()).hexdigest()
    myurl = myurl + '?appid=' + appid + '&q=' + urllib.parse.quote(q) + '&from=' + fromLang + '&to=' + toLang + '&salt=' + str(salt) + '&domain=' + domain + '&sign=' + sign

    try:
        httpClient = http.client.HTTPConnection('api.fanyi.baidu.com')
        httpClient.request('GET', myurl)

        # response
        response = httpClient.getresponse()
        result_all = response.read().decode("utf-8")
        result = json.loads(result_all)
        dst_string = result["trans_result"][0]["dst"]
        return dst_string
        # print(dst_string)

    except Exception as e:
        print(e)
    finally:
        if httpClient:
            httpClient.close()
